//
//  ViewController.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/6/23.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "MainViewController.h"
#import "DDNetWorkAPIClient.h"
//#import "DDAnswerRootVC.h"
#import "DDTabEncryptionVC.h"
//#import "DDQuestionsRootVC.h"
#import "DDTabRewardVC.h"
//#import "DDMessageRootVC.h"
#import "DDTabHelpVC.h"
#import "DDWoRootVC.h"
#import "GlobalDefine.h"

#import "QCLeftMenuViewController.h"
#import "MMDrawerController.h"
#import "MMDrawerVisualState.h"

#import "MWPhotoBrowser.h"

#import "DDPushDB.h"

#import "XGPush.h"
#import "AppDelegate.h"

#import "DDLoginRootVC.h"

#import "AFHTTPSessionManager.h"
@interface MainViewController ()<MWPhotoBrowserDelegate>
{
    //DDAnswerRootVC *_answerRootVC;
    DDTabEncryptionVC *_tabEncryptionVC;
    //DDQuestionsRootVC *_questionsRootVC;
    DDTabRewardVC *_tabRewardVC;
    //DDMessageRootVC *_messageRootVC;
    DDTabHelpVC *_tabHelpVC;
    DDWoRootVC *_woRootVC;
}
@property (nonatomic,strong)NSArray *photos;
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ToDetailPage:) name:@"ToDetailPage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DisPlayImage:) name:@"DisPlayImage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(relogin:) name:@"relogin" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removePushMessage:) name:@"removePushMessage" object:nil];
    //
    //    NSDictionary *params = @{@"userName":@"test01",@"phoneCode":@"13055284289",@"password":@"a123456",@"nickName":@"iosapp",@"platCode":@"ios",@"fid":@"123"};
    //    [network userRegister:params completionBlock:^(BOOL isSuccess, NSString *message, NSString *status) {
    //
    //    }];
    //DDSharedUser *user = [DDSharedUser shared];
    //[network userAuthToken:@"13055284289" password:@"a123456" CompletionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
        
   
//        [network userAuthToken:@{@"grant_type":@"password",@"client_id":@"app",@"client_secret":@"f50aa247a3e56eb5ee744a983e2ff9d5",@"username":@"test01",@"password":@"a123456"} CompletionBlock:^(BOOL isSuccess, NSDictionary *result, NSString *message, NSString *status) {
//
//            DDSharedUser *sharedUser = [DDSharedUser shared];
    //        [network userAuthToken:@{@"grant_type":@"refresh_token",@"client_id":@"app",@"client_secret":@"f50aa247a3e56eb5ee744a983e2ff9d5",@"refresh_token":sharedUser.refresh_token} CompletionBlock:^(BOOL isSuccess,NSDictionary *result, NSString *message, NSString *status) {
    //
    //        }];
    //        [network userLoginOut:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
    //
    //        }];
    //    DDSharedUser *user = [DDSharedUser shared];
    //           [network getUserInfo:user.access_token completionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
    
                   [self setupSubviews];//布局createUI
                   self.selectedIndex = 0;//默认选择第一项

   //            }];
    //    }];
    //    [network userPhoneCode:^(BOOL isSuccess, NSString *message, NSString *status) {
    //
    //    }];
    
    
    [network getUserInfo:nil completionBlock:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
        
    }];
    
    
    DDSharedUser *user = [DDSharedUser shared];
    NSString *uxgid = [user.userInfo.uid integerValue] < 10 ? [NSString stringWithFormat:@"0%ld",(long)[user.userInfo.uid integerValue]]:user.userInfo.uid;
    [XGPush setAccount:[NSString stringWithFormat:@"%@",uxgid]];
    
    AppDelegate *appdelegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
    [XGPush registerDeviceStr:appdelegate.deviceTokenStr];
    
   //切换token
   [NSTimer scheduledTimerWithTimeInterval:3600 target:self selector:@selector(changeToken) userInfo:nil repeats:YES];
    
    NSLog(@"appdelegate.deviceTokenStr=%@",appdelegate.deviceTokenStr);
    NSLog(@"user.userInfo.uid=%@",user.userInfo.uid);
    
    
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"text/html",nil];
        //2.准备参数
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        params[@"user_id"] = user.userInfo.uid;
        params[@"device_token"] = appdelegate.deviceTokenStr;
        [manager POST:@"http://www.dd5s.com/wap/dd10_api/login_app_logs.php" parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            if ([responseObject isKindOfClass:[NSDictionary class]])
            {
                if ([responseObject[@"add_login_log"] isEqual:@"success"])
                {
                    NSLog(@"用户手机识别码device_token登记成功！");
                }
            }else if([responseObject isKindOfClass:[NSArray class]]){
                
                NSLog(@"receive data type is NSArray");
                
            }
    
    
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error=%@",error.userInfo);
            NSLog(@"failure task=%@",task);
        }];
    
}

-(void)relogin:(NSNotification *)note
{
    UIViewController *rootViewController = [[DDLoginRootVC alloc]init];
    
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:rootViewController];
    
    AppDelegate *delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    delegate.window.rootViewController = nav;

}

-(void)changeToken
{
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    [network userRefreshAuthToken:^(BOOL isSuccess, NSDictionary *dict, NSString *message, NSString *status) {
        if (isSuccess) {
            NSLog(@"123123%@",dict);
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    
    
    NSInteger rowCount1 = [DDPushDB rowCountWithWhere:@"unread=0"];
    if (rowCount1 > 0) {
        UIImageView *dotImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"提醒-圆点-底"]];
        dotImage.backgroundColor = [UIColor clearColor];
        dotImage.tag = 100;
        CGRect tabFrame = self.tabBar.frame;
        CGFloat x = ceilf(0.69 * tabFrame.size.width);
        CGFloat y = ceilf(0.2 * tabFrame.size.height);
        dotImage.frame = CGRectMake(x, y, 6, 6);
        [self.tabBar addSubview:dotImage];
    }
}

- (void)removePushMessage:(NSNotification*)note
{
    [[self.view viewWithTag:100]removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark -private


- (void)setupSubviews
{
    
    //self.tabBar.backgroundColor = [UIColor clearColor];
    //self.tabBar.backgroundImage = [[UIImage imageNamed:@"tabbarBackground"] stretchableImageWithLeftCapWidth:25 topCapHeight:25];//拉伸图案
    //self.tabBar.selectionIndicatorImage = [[UIImage imageNamed:@"tabbarSelectBg"] stretchableImageWithLeftCapWidth:25 topCapHeight:25];//拉伸图案
    //self.tabBar.barTintColor = [UIColor clearColor];
    
    
    QCLeftMenuViewController *leftVC = [[QCLeftMenuViewController alloc]
                                        initWithNibName:@"QCLeftMenuViewController"
                                        bundle:nil];
    
    //回答
//    _answerRootVC = [[DDAnswerRootVC alloc]
//                     initWithCenterViewController:leftVC.navSlideSwitchVC
//                     leftDrawerViewController:nil
//                     rightDrawerViewController:nil];
//    [_answerRootVC setMaximumLeftDrawerWidth:160.0];
//    [_answerRootVC setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
//    [_answerRootVC setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
//    [_answerRootVC setDrawerVisualStateBlock:^(MMDrawerController *drawerController, MMDrawerSide drawerSide, CGFloat percentVisible) {
//        MMDrawerControllerDrawerVisualStateBlock block;
//        block = [MMDrawerVisualState parallaxVisualStateBlockWithParallaxFactor:2.0];
//        block(drawerController, drawerSide, percentVisible);
//    }];
//    _answerRootVC = [[DDAnswerRootVC alloc]initWithNibName:@"DDAnswerRootVC" bundle:nil];
//    _answerRootVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"加密"
//                                                             image:nil
//                                                               tag:0];
//    [_answerRootVC.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"bottom-答疑-02"]//点击图
//                           withFinishedUnselectedImage:[UIImage imageNamed:@"bottom-答疑"]];//未点击图
//    [self unSelectedTapTabBarItems:_answerRootVC.tabBarItem];//未点击字体属性
//    [self selectedTapTabBarItems:_answerRootVC.tabBarItem];//点击字体属性
    

    //回答改加密
    _tabEncryptionVC = [[DDTabEncryptionVC alloc]initWithNibName:@"DDTabEncryptionVC" bundle:nil];
    _tabEncryptionVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"加密"
                                                             image:nil
                                                               tag:0];
    [_tabEncryptionVC.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"jiami_p"]//点击图
                           withFinishedUnselectedImage:[UIImage imageNamed:@"jiami"]];//未点击图
    [self unSelectedTapTabBarItems:_tabEncryptionVC.tabBarItem];//未点击字体属性
    [self selectedTapTabBarItems:_tabEncryptionVC.tabBarItem];//点击字体属性
    

    
    //发问
//    _questionsRootVC = [[DDQuestionsRootVC alloc] init];
//    _questionsRootVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"悬赏"
//                                                                image:nil
//                                                                  tag:1];
//    [_questionsRootVC.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"bottom-发问-02"]//点击图
//                              withFinishedUnselectedImage:[UIImage imageNamed:@"bottom-发问"]];//未点击图
//    [self unSelectedTapTabBarItems:_questionsRootVC.tabBarItem];//未点击字体属性
//    [self selectedTapTabBarItems:_questionsRootVC.tabBarItem];//点击字体属性

    //悬赏
    _tabRewardVC = [[DDTabRewardVC alloc] init];
    _tabRewardVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"悬赏"
                                                                image:nil
                                                                  tag:1];
    [_tabRewardVC.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"xuanshang_p"]//点击图
                              withFinishedUnselectedImage:[UIImage imageNamed:@"xuanshang"]];//未点击图
    [self unSelectedTapTabBarItems:_tabRewardVC.tabBarItem];//未点击字体属性
    [self selectedTapTabBarItems:_tabRewardVC.tabBarItem];//点击字体属性
    
    
    //消息
//    _messageRootVC = [[DDMessageRootVC alloc] initWithNibName:nil bundle:nil];
//    _messageRootVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"晒晒"
//                                                              image:nil
//                                                                tag:4];
//    [_messageRootVC.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"shaishai_p"]
//                            withFinishedUnselectedImage:[UIImage imageNamed:@"shaishai"]];
//    [self unSelectedTapTabBarItems:_messageRootVC.tabBarItem];
//    [self selectedTapTabBarItems:_messageRootVC.tabBarItem];
    
    //大家帮改晒晒
        _tabHelpVC = [[DDTabHelpVC alloc] initWithNibName:nil bundle:nil];
        _tabHelpVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"晒晒"
                                                                  image:nil
                                                                    tag:4];
        [_tabHelpVC.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"shaishai_p"]
                                withFinishedUnselectedImage:[UIImage imageNamed:@"shaishai"]];
        [self unSelectedTapTabBarItems:_tabHelpVC.tabBarItem];
        [self selectedTapTabBarItems:_tabHelpVC.tabBarItem];
    
    //我
    _woRootVC = [[DDWoRootVC alloc] initWithNibName:nil bundle:nil];
    _woRootVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我"
                                                         image:nil
                                                           tag:2];
    [_woRootVC.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"wo_p"]
                       withFinishedUnselectedImage:[UIImage imageNamed:@"wo"]];
    [self unSelectedTapTabBarItems:_woRootVC.tabBarItem];
    [self selectedTapTabBarItems:_woRootVC.tabBarItem];
    
    
    
    UINavigationController *navAnswer = [[UINavigationController alloc] initWithRootViewController:_tabEncryptionVC];
    UINavigationController *navQuestion = [[UINavigationController alloc] initWithRootViewController:_tabRewardVC];
    UINavigationController *navMessage = [[UINavigationController alloc] initWithRootViewController:_tabHelpVC];
    UINavigationController *navWo = [[UINavigationController alloc] initWithRootViewController:_woRootVC];
    
    self.viewControllers = @[navAnswer,navQuestion,navMessage,navWo];
    
    self.tabBar.tintColor=RGB(42, 187, 240);
    self.tabBar.barTintColor = [UIColor whiteColor];
    navAnswer.navigationController.navigationBarHidden = YES;
    [self setSelectedViewController:navAnswer];
}


-(void)unSelectedTapTabBarItems:(UITabBarItem *)tabBarItem//未点击字体属性
{
        [tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                            [UIFont systemFontOfSize:15], UITextAttributeFont,RGB(146, 146, 146),UITextAttributeTextColor,
                                            nil] forState:UIControlStateNormal];
}

-(void)selectedTapTabBarItems:(UITabBarItem *)tabBarItem//点击字体属性
{
    [tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                        [UIFont systemFontOfSize:15],
                                        UITextAttributeFont,RGB(42, 187, 240),UITextAttributeTextColor,
                                        nil] forState:UIControlStateSelected];
}



- (void) ToDetailPage:(NSNotification*) note
{
    UIViewController *controller = note.object;
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)DisPlayImage:(NSNotification *)note
{
    _photos = note.object;
    // Create browser
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.zoomPhotosToFill = YES;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
    browser.wantsFullScreenLayout = YES;
#endif
    browser.enableSwipeToDismiss = YES;
    [browser setCurrentPhotoIndex:0];
    [self.navigationController pushViewController:browser animated:YES];
    //[self presentViewController:browser animated:YES completion:nil];
}
#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.photos.count)
        return [self.photos objectAtIndex:index];
    return nil;
}
@end
